#include "StdAfx.h"
#include "ReminderSyncTask.h"
#include "../omsproxy/OMSClientBase.h"
#include "../omsproxy/OMSClientConcrete.h"
#include "Helper.h"
#include "../commonlib/Log.h"

#include <sstream>


ReminderSyncTask::ReminderSyncTask(Outlook::_Application* spAppCache)
{
	m_app = spAppCache;
	//if(!regesiter)
	//	regesiter = new Regesiter();
}

ReminderSyncTask::ReminderSyncTask(void)
{
}


ReminderSyncTask::~ReminderSyncTask(void)
{
}


void * ReminderSyncTask::run(void * param)
{
	while(1){
		std::wstring serviceProvider;
		std::wstring serviceUri;
		std::wstring userEmail;
		std::wstring reminderPhone;
		bool EnableContact;
		bool EnableReminder;
		LogDebug(_T("Step in ReminderSyncTask"));
		try{
			if(regesiter.LoadSyncServiceInfo(serviceProvider,serviceUri,userEmail,reminderPhone,EnableContact,EnableReminder) == ERROR_SUCCESS){
				if(EnableReminder){
					//std::wstring owner;
					//if(m_app->Version.Detach()[1] < '4'){
					//	owner = m_app->Session->CurrentUser->Address;
					//}
					//else if(m_app->Version.Detach()[1] == '2' && m_app->Version.Detach()[7] < '6'){
					//	owner = m_app->Session->CurrentUser->Address;
					//}
					//for 2010
					//else{

					//auto objAddressEntry  = m_app->GetNamespace(L"MAPI")->CurrentUser;
					//auto user = objAddressEntry->AddressEntry->GetExchangeUser();
					//	auto usersmtp = user->PrimarySmtpAddress;
					//owner = (wchar_t*)usersmtp;
					//}
					LogDebug(_T("Outlook::_RemindersPtr reminders = m_app->GetReminders();"));
					Outlook::_RemindersPtr reminders = m_app->GetReminders();
					LogDebug(_T("long nCount = reminders->Count;"));
					long nCount = reminders->Count;
					std::wstring entryID;
					std::wstring subject;
					std::wstring responseData;
					//!!!!!!!!!!!dispose
					LogDebug(_T("std::vector<Reminder*>* localreminders = new std::vector<Reminder*>();"));
					std::vector<Reminder*>* localreminders = new std::vector<Reminder*>();
					LogDebug(_T("std::wstring* Buildresult = new std::wstring();"));
					std::wstring* Buildresult = new std::wstring(); // since this may be very big , so put it in heap

					//---get local reminders
					LogDebug(_T("for( long i = 1 ; i <= nCount ; i++ )"));
					for( long i = 1 ; i <= nCount ; i++ )
					{
						LogDebug(_T("Outlook::_ReminderPtr each = reminders->Item(_variant_t(i));"));
						Outlook::_ReminderPtr each = reminders->Item(_variant_t(i));
						LogDebug(_T("Reminder* reminder = new Reminder();"));
						Reminder* reminder = new Reminder();
						LogDebug(_T("reminder->ReminderTime = each->OriginalReminderDate;"));
						reminder->ReminderTime = each->OriginalReminderDate;
						LogDebug(_T("if(Outlook::_AppointmentItemPtr item = each->Item){"));
						if(Outlook::_AppointmentItemPtr item = each->Item){
							LogDebug(_T("1"));
							reminder->EntryID = item->EntryID;
							reminder->Content = item->Subject;
							reminder->StartTime = item->Start;
							reminder->EndTime = item->End;
							LogDebug(_T("2"));
						}
						else if(Outlook::_MeetingItemPtr item = each->Item){
							LogDebug(_T("3"));
							reminder->EntryID = item->EntryID;
							reminder->Content = item->Subject;
							LogDebug(_T("4"));
						}
						else if(Outlook::_TaskItemPtr item = each->Item){
							LogDebug(_T("5"));
							reminder->EntryID = item->EntryID;
							reminder->Content = item->Subject;
							LogDebug(_T("6"));
						}

						LogDebug(_T("if(reminder->EntryID.empty()){"));
						if(reminder->EntryID.empty()){
							LogDebug(_T("delete reminder;"));
							delete reminder;
							LogDebug(_T("delete reminder;"));
							continue;
						}
						else{
							LogDebug(_T("localreminders->push_back(reminder);"));
							localreminders->push_back(reminder);
						}
					}
					//---get syncserviceinfo
					//std::wstring serviceProvider;
					//std::wstring serviceUri;
					//std::wstring userEmail;
					//std::wstring reminderMobile;
					//bool enableC;
					//bool enableR;
					//if(regesiter.LoadSyncServiceInfo(serviceProvider,serviceUri,userEmail,reminderMobile,enableC,enableR) != 0) goto error_release;
					LogDebug(_T("BuildReminderRequest(localreminders,userEmail,reminderPhone,*Buildresult);"));
					BuildReminderRequest(localreminders,userEmail,reminderPhone,*Buildresult);
					//MessageBoxW(0,Buildresult->c_str(), L"1",0);

					LogDebug(_T("OMSClientBase* client = (OMSClientBase*)new OMSClientConcrete(); "));
					OMSClientBase* client = (OMSClientBase*)new OMSClientConcrete(); 

					LogDebug(_T("if(client->SetReminder(serviceUri,userEmail,reminderPhone,*Buildresult,responseData) == 0){"));
					if(client->SetReminder(serviceUri,userEmail,reminderPhone,*Buildresult,responseData) == 0){
						LogDebug("Remote invoke success!");
					}
					else{
						LogDebug(Buildresult->c_str());
					}

					//final realse
error_release:
					LogDebug(_T("if(!localreminders) continue;"));
					if(!localreminders) continue;
					LogDebug(_T("for(std::vector<Reminder*>::iterator i = localreminders->begin();"));
					for(std::vector<Reminder*>::iterator i = localreminders->begin();
						i != localreminders->end();
						i++){
							delete (*i);
							(*i) = NULL;
					}
					LogDebug(_T("delete localreminders;"));
					delete localreminders;
					LogDebug(_T("delete Buildresult;"));
					delete Buildresult;
					LogDebug(_T("delete client;"));
					delete client;
				}
			}
		}
		catch(...){
			LogDebug(_T("ReminderSyncTask Catch Exception"));
		}
#ifdef _DEBUG
		sleep(20000);
#else
		sleep(1000*60*10);
#endif
	}
	return NULL;
}

//<?xml version="1.0" encoding="utf-16"?>
//<reminderData>
//  <user>
//    <Owner>parkerz@wicresoft.com</Owner>
//    <Mobile>abc</Mobile>
//  </user>
//  <reminder>
//    <EntryID>abc</EntryID>
//    <Content>abc</Content>
//    <ReminderTime>4433.26</ReminderTime>
//    <StartTime>4433.26</StartTime>
//    <EndTime>4433.26</EndTime>
//  </reminder>
//  <reminder>
//    <EntryID>abc</EntryID>
//    <Content>abc</Content>
//    <ReminderTime>4433.26</ReminderTime>
//    <StartTime>4433.26</StartTime>
//    <EndTime>4433.26</EndTime>
//  </reminder>
//</reminderData>
LRESULT ReminderSyncTask::BuildReminderRequest(std::vector<Reminder*>* list,std::wstring& owner , std::wstring& mobile,std::wstring& result)
{
	LPCWSTR FramePattern = L"<?xml version=\"1.0\" encoding=\"utf-16\"?>\
							<reminderData>\
							<user>\
							<Owner>%s</Owner>\
							<Mobile>%s</Mobile>\
							</user>\
							%s\
							</reminderData>";
	LPCWSTR  SinglePattern = L"<reminder>\
							  <EntryID>%s</EntryID>\
							  <Content>%s</Content>\
							  <ReminderTime>%s</ReminderTime>\
							  <StartTime>%s</StartTime>\
							  <EndTime>%s</EndTime>\
							  </reminder>";
	if(list){
		std::wstring* siglereminders = new std::wstring();//!!desponse
		for(std::vector<Reminder*>::iterator iter = list->begin();
			iter != list->end();
			iter++)
		{
			wchar_t* singlebuffer = new wchar_t[1024];
			//
			std::wstringstream s1;
			std::wstringstream s2;
			std::wstringstream s3;
			s1.precision(15);
			s2.precision(15);
			s3.precision(15);
			s1 << (*iter)->ReminderTime;
			s2 << (*iter)->StartTime;
			s3 << (*iter)->EndTime;

			wsprintfW(singlebuffer,SinglePattern,(*iter)->EntryID.c_str(),EscapXml((*iter)->Content).c_str(), s1.str().c_str(),s2.str().c_str(),s3.str().c_str());
			siglereminders->append(singlebuffer);
			delete singlebuffer;
		}
		wchar_t* totalbuffer = new wchar_t[256 + siglereminders->length()];
		//memset(totalbuffer,0,(256 + siglereminders->length())*sizeof(wchar_t));
		_snwprintf(totalbuffer,256 + siglereminders->length(),FramePattern,owner.c_str(),mobile.c_str(),siglereminders->c_str());
		//wsprintfW(totalbuffer,FramePattern,owner.c_str(),mobile.c_str(),siglereminders->c_str());
		result.clear();
		result.append(totalbuffer);
		delete totalbuffer;
		delete siglereminders;
	}
	return 0;
}